package com.example.authdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.authdemo.dao.MenuMapper;
import com.example.authdemo.dao.UserMapper;
import com.example.authdemo.domain.LoginUser;
import com.example.authdemo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * ClassName: UserDetailsService
 * Package: com.example.authdemo.service
 * Description:
 *
 * @Author luohf
 * @Create 2023/7/11 19:04:37
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(wrapper);
        // 查询不到抛出异常
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名错误");
        }

        // 根据用户查询权限信息 添加到LoginUser中(现在是一个假的权限)
        //List<String> list = new ArrayList<>(Arrays.asList("sayhello", "delgoods"));
        List<String> perms = menuMapper.selectPermsByUserId(user.getId());

        // 封装成UserDetails对象返回
        return new LoginUser(user,perms);
    }
}
